package com.whz.workmanageol.controller;

import com.whz.workmanageol.entity.*;
import com.whz.workmanageol.service.*;
import com.whz.workmanageol.utils.FileUpload;
import com.whz.workmanageol.vo.FilePath;
import com.whz.workmanageol.vo.StudentWorkVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * 教师的Controller
 */
@Controller
@RequestMapping(value = "/teacher")
public class TeacherController {
    private static final Logger logger = LoggerFactory.getLogger(TeacherController.class);
    @Autowired
    private PublishService publishService;
    @Autowired
    private WorkService workService;
    @Autowired
    private FileUpload fileUpload;
    @Autowired
    private GradeService gradeService;
    @Autowired
    private CourseService courseService;
    @Autowired
    private TeacherService teacherService;

    @GetMapping(value = "gotopublish")
    public String goToPublish(HttpServletRequest request){
        String gradeid = request.getParameter("gradeid");
        String courseid = request.getParameter("courseid");
        request.getSession().setAttribute("gradeid" , gradeid);
        request.getSession().setAttribute("courseid" , courseid);
        return "bootstrap/publish";
    }

    @PostMapping(value = "publish")
    public String publishWork(HttpServletRequest request,
                              HttpServletResponse response,
                              Publish publish,
                              @RequestParam("file") MultipartFile file){
        User user = (User) request.getSession().getAttribute("user");
        if(!"teacher".equals(user.getRole())){
            throw new IllegalArgumentException("当前账号的角色不是教师,无权发布作业");
        }
        // 上传作业对应的本地文件操作
        String gradeid = (String) request.getSession().getAttribute("gradeid");
        String courseid = (String) request.getSession().getAttribute("courseid");
        Long seq = publishService.countTeacherPub(new FilePath(user.getId(), gradeid, courseid, null));
        FilePath filePath = new FilePath(user.getId(), gradeid, courseid, seq+"");
        fileUpload.teacherPublish(file, filePath);
        // 上传文件保存到数据库
        if(!("".equals(file.getOriginalFilename()))){
            publish.setHasattach("1");
        }
        publishService.publishDB(filePath, publish);
        // 生成的作业信息保存到数据库
        try {
            response.setContentType("text/html;charset=utf-8");
            String url = "作业已发布,请关闭该弹窗并刷新发布页面";
            response.getWriter().write("<script>alert('作业发布成功！');</script>");
            response.getWriter().flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "bootstrap/index";
    }

    /**
     * 展示指定 教师ID 班级ID 课程ID 确认布置的作业
     * @return
     */
    @GetMapping(value = "gotopublishlist")
    public String goToPublishlist(HttpServletRequest request, Model model){
        String gradeid = request.getParameter("gradeid");
        String courseid = request.getParameter("courseid");
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        List<Publish> publishList = publishService.publishList(user.getId(), gradeid, courseid);
        model.addAttribute("publishList", publishList);
        Grade grade = gradeService.findGradeById(gradeid);
        Course course = courseService.findCourseById(courseid);
        request.getSession().setAttribute("grade", grade);
        request.getSession().setAttribute("course", course);
        return "bootstrap/publishlist";
    }



    @GetMapping("worklist")
    public String workList(HttpServletRequest request, Model model){
        String publishid = request.getParameter("publishid");
        List<StudentWorkVO> studentWorkVOList = workService.studentWorkList(publishid);
        model.addAttribute("studentWorkVOList", studentWorkVOList);
        return "bootstrap/worklist";
    }

    @ResponseBody
    @GetMapping(value = "saveScore")
    public void saveScore(HttpServletRequest request){
        String workid = request.getParameter("workid");
        String scoreNum = request.getParameter("score");
        logger.info("workid: {}   score: {}", workid,scoreNum);
        workService.saveScore(workid, scoreNum);
    }
    @ResponseBody
    @PostMapping(value = "/findOne")
    public Teacher findOne(String id){
        return teacherService.findTeacherById(id);
    }

}
